<template>
  <div>
    <n-space justify="space-between">
      <n-space>
        <n-dropdown trigger="click" :options="dropOptions" @select="handleSelect">
          <n-button size="small" type="info">分镜选择</n-button>
        </n-dropdown>
        <n-divider vertical></n-divider>
        <n-button
            size="small"
            type="info"
            style="margin-bottom: 10px;"
            @click="batchRewrite">
          批量改写
        </n-button>
        <n-gradient-text  :size="18" type="info" v-if="checkedRowKeysRef">
          选中{{  checkedRowKeysRef.length }}行
        </n-gradient-text>
        <progressLite
            v-if="taskStatus.totalNum>0"
            :totalNum="taskStatus.totalNum"
            :successNum="taskStatus.successNum"
            :failNum="taskStatus.failNum"
            :pauseFlag="pauseFlag"
            :pauseTask="pauseTask"
            :continueTask="continueTask"
            :cancelTask = "cancelTask"></progressLite>
      </n-space>
      <n-space>
        <n-button type="primary" @click="saveRewrite">保存改写分镜</n-button>
      </n-space>
    </n-space>
    <n-data-table
        ref="storyBoardTableRef"
        :single-line="false"
        :bordered="true"
        :loading="tableLoading"
        :row-key="(row)=>{
          return row.id
        }"
        :bottom-bordered="true"
        :columns="createColumns"
        :checked-row-keys="checkedRowKeysRef"
        :data="boardList"
        :style="{ height: `${clientHeight - 129}px` }"
        flex-height
        @update:checked-row-keys="handleCheck"
    />
  </div>
</template>
<script setup lang="ts">
import {
  NButton,
  NImage,
  NInput,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui'
import {h, onMounted, ref} from "vue"
import {storyController} from "@/api/story/story.api"
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"
import {creatorDict} from '@/dictionary/creatorDict'
import {gptControllerApi} from "@/api/chat/gptController.api";
import progressLite from '@/components/progress/ProgressLite.vue'
import {storySentenceController} from "@/api/controller/story/storySentenceController.api";


const message = useMessage()
const tableLoading = ref(false)
const currentTaskNum = ref(0)
const boardList = ref([])
const audio = ref(null)
const drawerWidth = ref(0)

const storyBoardSelectOption = ref("0")
const storyBoardTableRef = ref(null)
const resourceId = ref(null)
const paintConfig = ref(null)
const stopLoop = ref(false)
const pauseFlag = ref(false)
const skipFlag = ref(true)
const voiceConfig = ref(null)
const checkedRowKeysRef = ref([])

const dropOptions =ref([
  {
    label: '前10条',
    key: '1'
  },
  {
    label: '前20条',
    key: "2"
  },
  {
    label: '前30条',
    key: '3'
  },
  {
    label: '所有',
    key: '4'
  }
])


const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

const rewriteOptions  = ref<Array<any>>([
  {
    label: '全部',
    value: '0'
  },
  {
    label: '已改写',
    value: '1'
  },
  {
    label: '未改写',
    value: '2'
  }
])


// 任务状态
const taskStatus = ref({
  successNum: 0,
  failNum: 0,
  totalNum: 0
})

const props = defineProps({
  storyId: {
    type: Object,
    default: () => {
      return {}
    }
  },
  closeAction:{
    type: Function,
    default: () => {}
  }
})




// 列表字段
const createColumns = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'orderNum',
    width: 40,
    titleAlign: 'center'
  },
  {
    title: '原文',
    key: 'content',
    width: 200,
    titleAlign: 'center',
    render(row, index) {
      return h(NInput, {
        value: row.content,
        type: 'textarea',
        style: 'height: 100px'
      })
    }
  },
  {
    title: '改文',
    key: 'rewriteContent',
    width: 200,
    titleAlign: 'center',
    render(row, index) {
      return h(NInput, {
        value: row.rewriteContent,
        onUpdateValue (v) {
          boardList.value[index].rewriteContent = v
        },
        type: 'textarea',
        style: 'height: 100px'
      })
    }
  },
  {
    title: '参考图',
    key: 'prompt',
    width: 150,
    align: 'center',
    render(row) {
      return h(NImage, {
        lazy: true,
        height: '100',
        src: fileFunction.getViewFilePathByUserFileId(row.examplePic)
      })
    }
  },
  {
    title: '操作',
    width: 60,
    align: 'center',
    render(row, index) {
      return [
        h(NButton, {
          size: 'small',
          block: true,
          loading: row.rewriteLoading,
          type: 'info',
          onClick: () => synonymRewrite(row)
        }, {
          default: () => '改写'
        })
      ]
    }
  }
]




const getStoryBoardByChapterId = () => {
  tableLoading.value = true
  storyController.getStoryScheduleByChapterId(props.storyId, storyBoardSelectOption.value).then(res => {
    tableLoading.value = false
    if (res.code === 200) {
      boardList.value = res.data
    } else {
      message.error(res.msg)
    }
  })
}

onMounted(() => {
  getStoryBoardByChapterId()
})


const handleCheck = (rowKeys: [])=> {
  checkedRowKeysRef.value = rowKeys
}


const handleSelect = (option:any) => {
  checkedRowKeysRef.value = []
  if (option==='1'){
    boardList.value.slice(0,10).forEach((item:any)=>{
      checkedRowKeysRef.value.push(item.id)
    })
  }else if (option==='2') {
    boardList.value.slice(0, 20).forEach((item: any) => {
      checkedRowKeysRef.value.push(item.id)
    })
  }else if (option==='3') {
    boardList.value.slice(0, 30).forEach((item: any) => {
      checkedRowKeysRef.value.push(item.id)
    })
  }else {
    boardList.value.forEach((item: any) => {
      checkedRowKeysRef.value.push(item.id)
    })
  }
}



const synonymRewrite = (row: any) => {
  let content = row.content
  row.rewriteLoading = true
  gptControllerApi.rewriteStoryContent(content).then(res => {
    if (res.code === 200) {
      if (res.data.optimizedCopy != null && res.data.optimizedCopy.length > 0 && res.data.optimizedCopy != 'null') {
        row.rewriteContent = res.data.optimizedCopy
      }
    }
  }).finally(() => {
    row.rewriteLoading = false
  })
}


// 更新改写内容
const saveRewrite = () => {
  const rewriteList = [] as any
  boardList.value.forEach((item: any) => {
    if (item.rewriteContent != null && item.rewriteContent.length > 0) {
      rewriteList.push({
        id: item.id,
        content: item.rewriteContent
      })
    }
  })
  storySentenceController.rewriteStoryBoard(rewriteList).then(res => {
    if (res.code === 200) {
      props.closeAction()
    }
  })
}



const batchRewrite = async () => {
  if (checkedRowKeysRef.value.length === 0) {
    message.info("请先选择改写的分镜!!")
    return
  }
  stopLoop.value = false
  currentTaskNum.value = 0
  taskStatus.value = {
    successNum: 0,
    failNum: 0,
    totalNum: checkedRowKeysRef.value.length
  }
  for (const storyBoardId of checkedRowKeysRef.value) {
    if (stopLoop.value) {
      taskStatus.value.totalNum = 0
      taskStatus.value.successNum = 0
      taskStatus.value.failNum = 0
      pauseFlag.value = false
      break
    }

    const storyBoard = boardList.value.find((item: any) => item.id === storyBoardId)
    storyBoard.rewriteLoading = true
    currentTaskNum.value++
    try {
      const res = await gptControllerApi.rewriteStoryContent(storyBoard.content)
      storyBoard.rewriteLoading = false
      if (res.code === 200) {
        if (res.data.optimizedCopy != null && res.data.optimizedCopy.length > 0 && res.data.optimizedCopy != 'null') {
          storyBoard.rewriteContent = res.data.optimizedCopy
          taskStatus.value.successNum++
        }else {
          taskStatus.value.failNum++
        }
      }else {
        taskStatus.value.failNum++
      }
    } catch (e) {
      storyBoard.rewriteLoading = false
      taskStatus.value.failNum++
      message.error("系统异常,请稍后再试")
    }
  }
}




const pauseTask = () => {
  pauseFlag.value = true
}

const continueTask = () => {
  pauseFlag.value = false
}

const cancelTask = () => {
  stopLoop.value = true
}

</script>
